<?php

namespace app\core\middleware;

use app\core\Request;
use app\core\Response;
use app\service\UserService;

class Permission
{
    /**
     * 绕过权限验证
     * @var array
     */
    protected $ignore = [];

    public function handle(Request $request, \Closure $next, $ignore = [])
    {
        $this->ignore = array_merge($this->ignore, $ignore);
        $perm = $request->getPerm();
        if (!empty($perm)){
            // 超级管理员不需要鉴权
            if (!in_array($perm, $this->ignore) && !$request->isSuperAdmin()){
                $user = $request->getUser();
                if (empty($user)){
                    Response::invoke()->invalidError();
                }
                $perms = UserService::invoke()->getPermissions($user['user_id']);
                if (!in_array($perm, $perms)){
                    Response::invoke()->permissionError();
                }
            }
        }
        return $next($request);
    }

}